<script setup lang="ts">
import {
     nextTick,
     onBeforeUnmount,
     onMounted,
     ref,
     toRef,
     watch,
     defineProps,
     defineExpose,
} from 'vue'
//@ts-ignore
import { EChartOption, ECharts } from 'echarts'
import * as echarts from 'echarts'

const chartRef = ref<HTMLDivElement>()
let instance: ECharts | null = null

defineExpose({
     resize,
     setOption,
})
const props = defineProps<{ options: any }>()
const options = toRef(props, 'options')
watch(options, (value) => {
     setOption(value)
})
onMounted(() => {
     instance = echarts.init(chartRef.value as HTMLDivElement, 'dark', {
          locale: 'ZH',
     })

     nextTick(() => {
          setOption(options.value)
     })
})

function resize() {
     instance?.resize()
}

function setOption(option?: EChartOption, clear = true) {
     if (!option || !instance) return
     if (clear) instance.clear()
     // const padding = '5%'
     // option.grid = {
     //     top: '20%',
     //     bottom: padding,
     //     right: padding,
     //     left: padding,
     //     containLabel: true,
     // }
     option.backgroundColor = 'transparent'
     instance.setOption(option)
}

nextTick(() => {
     window.addEventListener('resize', () => {
          resize()
     })
})
onBeforeUnmount(() => {
     window.removeEventListener('resize', () => {
          resize()
     })
     instance?.dispose()
})
</script>
<template>
     <div ref="chartRef" class="chart-container" />
</template>

<style lang="scss" scoped>
.chart-container {
     width: 100%;
     height: 100%;
}
</style>
